<template>
	<div></div>
</template>

<script>
	import {
		OpenVidu
	} from "openvidu-browser";
	import {
		joinMeetingRoom,
		leaveMeetingRoom,
	} from '@/api'
	import {
		getToken
	} from '@/utils/auth.js'
	export default {
		props: {
			code: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				OV: undefined,
				session: undefined,
				publisher: undefined,
				userToken: ''
			}
		},
		computed: {
			user() {
				return this.$store.state.user || {}
			}
		},
		created() {
			this.userToken = getToken()
		},
		mounted() {
			this.OV = new OpenVidu(); // 获取RTC操作对象
			this.session = this.OV.initSession(); // 初始化会话对象
			this.session.on("streamCreated", this.onStreamCreated); // 监听人员加入
			this.session.on("streamDestroyed", this.onStreamDestroyed); // 监听人员离开
			this.session.on("exception", this.onException); // 监听异常情况
			this.session.on('signal:confirm', this.onJoinConfirm); // 接收会议消息
		},
		beforeDestroy() {
			this.onDispose()
		},
		methods: {
			async onInit() {
				const res = await joinMeetingRoom({
					meetingRoomCode: this.code
				})
				await this.session.connect(res.data.connectionToken, this.user)

				let publisher = this.OV.initPublisher(undefined, {
					publishAudio: false, // 关闭音频
					publishVideo: false, // 关闭视频
				});

				publisher.once('accessAllowed', (event) => {
					this.session.publish(publisher);
					this.publisher = publisher
					window.addEventListener("beforeunload", this.onDispose); // 监听页面卸载 关闭会话
				});
			},
			onDispose() {
				if (this.session) this.session.disconnect();
				if (this.publisher) {
					const connectionId = this.publisher.stream.connection.connectionId
					this.onLeave(connectionId)
				}
				this.session = undefined;
				this.publisher = undefined;
				this.OV = undefined;

				window.removeEventListener("beforeunload", this.leaveSession); // 移除页面卸载监听
			},
			onJoinConfirm(e) {
				console.log(e);
			},
			onLeave(connectionId) {
				leaveMeetingRoom({
					meetingRoomCode: this.code,
					connectionId
				}, {
					'user-token': this.userToken
				})
			},
			send() {
				this.session.signal({
					data: JSON.stringify({
						meetting: true,
						userId: this.user.id
					}), // 消息数据
					type: 'confirm' // 消息类型
				})
			},
			// 人员进入处理事件
			onStreamCreated(e) {
				console.log('监听人员进入', e);
				const user = this.getUser(e.stream)
				console.log(user);
			},
			// 人员离开处理事件
			onStreamDestroyed(e) {
				console.log('监听人员离开', e);
				console.log(e);
			},
			// 异常情况处理事件
			onException(e) {
				console.warn(e.exception);
			},
			getUser(stream) {
				return JSON.parse(stream.connection.data.split('%')[0])
			}
		}
	}
</script>

<style lang="scss" scoped>
</style>